package sn_log.worker;

import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat; 

import soar.basic.*;

import sn_log.share.Cnfg;

class LOG
{
    private String __CLASS__=LOG.class.getName();

    public boolean call(String ip, String filename, String msg)
    {//{{{
        Cnfg cnfg=Cnfg.getInstance();
        String dir=cnfg.customlog.location+"/"+ip;
        File d=new File(dir);
        if(d.exists())
        {
            if(!d.isDirectory() ||
                    !d.canRead() || !d.canWrite() || !d.canExecute())
            {
                Errlog.add(__CLASS__+": ip dir("+dir+") invalid");
                return false;
            }
        }
        else
        {
            if(!d.mkdir())
            {
                Errlog.add(__CLASS__+": create ip dir("+dir+") fail");
                return false;
            }
        }

        Date date=new Date();
        String file=dir+"/"+filename+".log."+
                    (new SimpleDateFormat("yyyyMMdd")).format(date);
        String date_s=(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).
            format(date);
        FileWriter log=null;
        try
        {
            log=new FileWriter(file, true);
            log.write(date_s+" -- "+msg+"\n");
        }
        catch(Exception e)
        {
            Errlog.add(__CLASS__+": write("+file+") fail:"+
                    e.toString());
            return false;
        }
        finally
        {
            try
            {
                if(log != null)
                    log.close();
            }
            catch(Exception e)
            {
                Errlog.add(__CLASS__+": close("+file+") fail:"+
                        e.toString());
                return false;
            }
        }

        return true;
    }//}}}
}
